<template>
  <div id="map"></div>
</template>

<script>
// var map = new AMap.Map('map', {
//     zoom: 11, //级别
//     center: [116.397428, 39.90923] //中心点坐标
// });
// var marker = new AMap.Marker({
//     position: new AMap.LngLat(116.39, 39.9), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
//     title: '北京',
//     draggable: true
// });

// // 将创建的点标记添加到已有的地图实例：
// marker.on('dragend', () => {
//     console.log(marker.getPosition());
// });
export default {
  name: '',
  data () {
    return {
      map: '',
      marker: '',
      newLng: '',
      newLat: '',
      search: ''
    };
  },
  props: ['address', 'latLng'],
  mounted () {
    if (this.address) {
      this.search = this.address;
      this.getCityCode();

    } else {
      this.newLng = parseFloat(this.latLng.lng);
      this.newLat = parseFloat(this.latLng.lat);
      console.log(this.latLng);
      this.getMap();
    }
    console.log(this.newLng, this.newLat, 'this.newLng')
  },
  methods: {
    getMap () {
      this.map = new AMap.Map('map', {
        zoom: 11, //级别
        // c {Q: 27.828829644876265, R: 113.13277901649474, lng: 113.132779, lat: 27.82883}
        center: [this.newLng || 113.132779, this.newLat || 27.82883] //中心点坐标
      });
      console.log(this.newLng, this.newLat);
      console.log(this.map);

      this.marker = new AMap.Marker({
        position: new AMap.LngLat(this.newLng || 113.132779, this.newLat || 27.82883), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        title: '',
        draggable: false
      });
      this.map.add(this.marker);
      // 将创建的点标记添加到已有的地图实例：
    },
    getCityCode () {
      let that = this;
      AMap.plugin('AMap.Geocoder', function () {
        var geocoder = new AMap.Geocoder({
          // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          city: ''
        })
        console.log(that.search);
        if (that.search) {
          geocoder.getLocation(that.search, function (status, result) {
            console.log(status, 'status');

            if (status === 'complete' && result.info === 'OK') {
              // result中对应详细地理坐标信息
              console.log(result);
              console.log(111)
              that.newLng = result.geocodes[0].location.lng;
              that.newLat = result.geocodes[0].location.lat;
              that.getMap();
            } else {
              that.getMap();
            }
          })
        } else {
          that.getMap();
        }
      })
    }
  }
};
</script>

<style scoped>
#map {
    width: 100%;
    height: 100%;
    /* background: rgba(237, 237, 237, 1); */
    opacity: 1;
}
</style>